<template lang="pug">
.view.cp-manage-provider.fix-flex-pos
  //- 查询
  el-form.pr-search(:inline="true")
    //- el-form-item
    //-   el-input(v-model="providerName", placeholder="编码/名称/拼首码", style="width: 160px")
    el-form-item(label="类别 : ")
      el-select(v-model="providerCate", placeholder="请选择", style="width: 120px")
        el-option(v-for="item in vendorCateSelectAll", :key="item.value", :label="item.name", :value="item.value")
    el-form-item(label="分级 : ")
      el-select(v-model="providerGrade", placeholder="请选择", style="width: 120px")
        el-option(v-for="item in vendorGradeSelectAll", :key="item.value", :label="item.name", :value="item.value")
    el-form-item(label="状态 : ")
      el-select(v-model="providerStatus", placeholder="请选择", style="width: 120px")
        el-option(v-for="item in statusSelectAll", :key="item.value", :label="item.name", :value="item.value")
    el-form-item
      el-button(type="primary", @click="searchProviders") 搜索
    el-form-item
      el-button(type="primary", @click="resetSearch", plain) 重置
    el-form-item
      el-button(type="primary", @click="addProvider") 新建供应商
  //- 列表
  .pr-table
    el-table(
      :data="providerList",
      highlight-current-row
      height="100%"
      size="mini"
      @row-dblclick="handleProviderRowDbClick"
      v-loading="loadingProviders")
      el-table-column(align="center", show-overflow-tooltip, type="index", :index="indexMethod", label="序号", :fixed="true")
      el-table-column(align="center", show-overflow-tooltip, prop="id", label="编码")
      el-table-column(align="center", show-overflow-tooltip, prop="name", label="名称")
      el-table-column(align="center", show-overflow-tooltip, prop="vendorcategory", label="类别")
        template(slot-scope="scope")
          span {{ scope.row.vendorcategory | compare-list(vendorCateSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="vendorgrade", label="分级")
        template(slot-scope="scope")
          span {{ scope.row.vendorgrade | compare-list(vendorGradeSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="characters", label="性质")
        template(slot-scope="scope")
          span {{ scope.row.characters | compare-list(vendorChatacterSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="scale", label="规模")
        template(slot-scope="scope")
          span {{ scope.row.scale | compare-list(scaleSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="registeredCapital", label="注册资金(万)", min-width="120px")
      el-table-column(align="center", show-overflow-tooltip, prop="registeredAddress", label="注册地址")
      el-table-column(align="center", show-overflow-tooltip, prop="status", label="状态")
        template(slot-scope="scope")
          span {{ scope.row.status | compare-list(statusSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="createUser", label="创建人")
        template(slot-scope="scope")
          span {{ scope.row.createUser | compare-list(empSelect) }}
      el-table-column(align="center", label="操作", min-width="90px")
        template(slot-scope="scope")
          el-tooltip(content="查看")
            i.icon-act.el-icon-view(@click="viewProvider(scope.row)")
          el-tooltip(content="编辑")
            i.icon-act.el-icon-edit(@click="eidtProvider(scope.row, scope.$index)")
          el-tooltip(content="删除")
            i.icon-act.el-icon-delete(@click="deleteProvider(scope.row, scope.$index)")
  //- 分页
  el-pagination.pr-pagination(
    layout="total, prev, pager, next, jumper",
    @current-change="changeProviderPage",
    :current-page.sync="currentPage",
    :page-size="pageSize",
    :total="providerListTotal")
  ProviderView(
    :visible="showProviderView",
    :formData="formData",
    @close="showProviderView=false")
  ProviderEdit(
    v-if="showProviderEdit",
    :visible="showProviderEdit",
    :formData="formData",
    @close="showProviderEdit=false",
    @save="saveProvider")
</template>

<script>
import { mapGetters } from 'vuex';
import ManApi from '@/api/manage';
import ProviderView from '@/components/manage/provider/ProviderView';
import ProviderEdit from '@/components/manage/provider/ProviderEdit';

export default {
  name: 'purprovider',
  data() {
    return {
      // 搜索条件
      // providerName: '',
      providerCate: null,
      providerGrade: null,
      providerStatus: null,
      // 供应商列表
      providerList: [],
      providerListTotal: 1,
      loadingProviders: true,
      currentPage: 1,
      pageSize: 20,
      // 物料
      formData: {},
      statusSelect: [
        { name: '启用', value: '0' },
        { name: '禁用', value: '1' }
      ],
      statusSelectAll: [
        { name: '全部', value: null },
        { name: '启用', value: '0' },
        { name: '禁用', value: '1' }
      ],
      showProviderView: false,
      showProviderEdit: false
    };
  },
  components: {
    ProviderView,
    ProviderEdit
  },
  computed: {
    ...mapGetters([
      'vendorChatacterSelect', 'vendorCateSelect', 'vendorCateSelectAll',
      'vendorGradeSelect', 'vendorGradeSelectAll', 'scaleSelect', 'empSelect'
    ])
  },
  methods: {
    indexMethod (i) {
      const size = this.pageSize || 20;
      return ((this.currentPage - 1) * size) + (i + 1);
    },
    // 弹层
    resetSearch () {
      this.providerName = null;
      this.providerCate = null;
      this.providerGrade = null;
      this.providerStatus = null;
    },
    makeSearch () {
      const params = {};
      if (typeof this.providerName !== 'object') {
        params.providerName = this.providerName;
      }
      if (typeof this.providerCate !== 'object') {
        params.vendorcategory = this.providerCate;
      }
      if (typeof this.providerGrade !== 'object') {
        params.vendorgrade = this.providerGrade;
      }
      if (typeof this.providerStatus !== 'object') {
        params.status = this.providerStatus;
      }

      return params;
    },
    searchProviders () {
      const params = this.makeSearch();
      this.loadingOrders = true;
      ManApi.getProviderList(params).then((result) => {
        if (!result.status) {
          this.providerList = result.obj.records;
          this.providerListTotal = result.obj.totalNum;
        } else {
          this.providerList = [];
          this.providerListTotal = 1;
          this.$message.error(result.comment);
        }
        this.loadingProviders = false;
      }).catch((error) => {
        this.loadingProviders = false;
        console.log(JSON.stringify(error));
      });
    },
    // 监听Provider列表事件
    handleProviderRowDbClick (row, event) {
      console.log(row, event);
    },
    // 新建供应商
    addProvider () {
      this.formData = {
        createDeptLevel1: '',
        createDeptLevel2: '',
        vendorContactList: [],
        vendorCredentialsList: [],
        vendorSupplyList: []
      };
      this.showProviderEdit = true;
    },
    viewProvider (row) {
      ManApi.getProviderDetail({ id: row.id }).then((result) => {
        if (!result.status) {
          this.formData = result.obj;
          this.showProviderView = true;
        } else {
          this.$message.error(result.comment);
        }
      }).catch((error) => {
        this.$message.error('请求失败，请稍后再试');
        console.log(JSON.stringify(error));
      });
    },
    eidtProvider (row, index) {
      // 表明编辑ID
      this.focusIndex = index;
      ManApi.getProviderDetail({ id: row.id }).then((result) => {
        if (!result.status) {
          this.formData = result.obj;
          this.showProviderEdit = true;
        } else {
          this.$message.error(result.comment);
        }
      }).catch((error) => {
        this.$message.error('请求失败，请稍后再试');
        console.log(JSON.stringify(error));
      });
    },
    deleteProvider (row, index) {
      this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loadingProviders = true;
        ManApi.deleteProvider({ id: row.id }).then((result) => {
          if (!result.status) {
            this.providerList.splice(index, 1);
            this.providerListTotal = this.providerListTotal - 1;
            this.$message.success('删除成功');
          } else {
            this.$message.error(`删除失败：${result.comment}`);
          }
          this.loadingProviders = false;
        }).catch((error) => {
          this.loadingProviders = false;
          console.log(JSON.stringify(error));
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    saveProvider () {
      // 处理资质相关物料
      const creditList = this.formData.vendorCredentialsList;
      creditList.forEach((item) => {
        item.skus = item.skus.join(',');
      });
      // 处理财务信息的结算币种
      const currencys = this.formData.settlementCurrency;
      this.formData.settlementCurrency = currencys.join(',');

      ManApi.saveProvider(this.formData).then((result) => {
        if (!result.status) {
          this.$message.success('保存成功');
          if (this.formData.vendorId) {
            this.$set(this.providerList, this.focusIndex, result.obj);
          } else {
            this.providerList.unshift({});
            this.$set(this.providerList, 0, result.obj);
            this.providerListTotal += 1;
            if (this.providerListTotal > 20) {
              this.providerList.pop();
            }
          }
          this.showProviderEdit = false;
        } else {
          this.$message.error(`保存失败：${result.comment}`);
          // 保存失败时，还原相关物料和结算币种的显示
          const errCreditList = this.formData.vendorCredentialsList;
          errCreditList.forEach((item) => {
            item.skus = item.skus.split(',');
          });

          const errCurrencys = this.formData.settlementCurrency;
          this.formData.settlementCurrency = errCurrencys.split(',');
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
        const errCreditList = this.formData.vendorCredentialsList;
        errCreditList.forEach((item) => {
          item.skus = item.skus.split(',');
        });

        const errCurrencys = this.formData.settlementCurrency;
        this.formData.settlementCurrency = errCurrencys.split(',');
      });
    },
    // 监听供应商翻页
    changeProviderPage (currentPage) {
      const params = this.makeSearch();
      params.pageNum = currentPage;
      this.loadingProviders = true;
      ManApi.getProviderList(params).then((result) => {
        if (!result.status) {
          this.providerList = result.obj.records;
          this.providerListTotal = result.obj.totalNum;
          this.currentPage = currentPage;
        } else {
          this.$message.error(result.comment);
        }
        this.loadingProviders = false;
      }).catch((error) => {
        this.loadingProviders = false;
        console.log(JSON.stringify(error));
      });
    },
  },
  beforeRouteEnter (to, from, next) {
    next();
  },
  created () {},
  mounted () {
    ManApi.getProviderList().then((result) => {
      if (!result.status) {
        this.providerList = result.obj.records;
        this.providerListTotal = result.obj.totalNum;
      } else {
        this.$message.error(result.comment);
      }
      this.loadingProviders = false;
    }).catch((error) => {
      this.loadingProviders = false;
      console.log(JSON.stringify(error));
    });
  }
};
</script>

<style lang="sass">
@import "../../../styles/utils"
$SEARCHHEIGHT: 56px
$PAGEHEIGHT: 56px
.cp-manage-provider
  .pr-search
    height: $SEARCHHEIGHT
    overflow-x: auto
    overflow-y: hidden
    padding: 12px 0 12px 16px
    .el-form-item
      margin-right: 14px
    .el-form-item__label
      padding-right: 6px
  .pr-table
    position: absolute
    top: $SEARCHHEIGHT
    bottom: $PAGEHEIGHT
    left: 16px
    right: 16px
    overflow: auto
    table
      &::before
        display: none
      .icon-act
        font-size: 16px
        margin-left: 3px
        margin-right: 3px
  .el-table
    .cell.el-tooltip
      user-select: text;
      div, span
        user-select: text;
  .pr-pagination
    position: absolute
    bottom: 16px
    left: 0
    right: 0
    text-align: center
</style>
